package com.leather.common.toolkits;


import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.File;

public class QinNiuKit {

    private final static String accessKey = "I2gQaU6X9A50KdLl1CDbey_f7aC4lyWHnXbm6xZv";
    private final static String secretKey = "e7j_G4rETOxT2TIlJ8V-gOSagrT9j5YOSSyHMQUd";
    private final static String bucketname = "kevinproject";
    //密钥配置
    private static Auth auth = Auth.create(accessKey, secretKey);
    //设置地区
    private static Configuration cfg = new Configuration(Zone.zone0());
    //新建文件上传管理器
    private static UploadManager uploadManager = new UploadManager(cfg);
    private static BucketManager bucketManager = new BucketManager(auth, cfg);

    public static String getStr(String type, File file) {
        //获取文件的后缀
        String fileName = file.getName();
        String extension = fileName.substring(fileName.lastIndexOf("."));
        //设置上传文件的名字
        String realName = type + System.currentTimeMillis() + extension;
        //用户鉴权
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucketname);
        try {
            Response response = uploadManager.put(file, realName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            throw new RuntimeException(r.toString());
        }
        return  realName;
    }

    public static boolean deleteImage(String fileName) {

        try {
            bucketManager.delete(bucketname, fileName);
            return true;
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            System.err.println(ex.code());
            System.err.println(ex.response.toString());
            return false;
        }
    }

}
